package com.cskaoyan.javase.object._3equals;

/**
 * 成员变量如果是引用数据类型如何比较对象相等呢?
 * 只需要再去重写该引用数据类型成员变量的equals方法即可
 *
 * @since 14:53
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Demo3 {
    public static void main(String[] args) {
        A a1 = new A("hello", new B(666));
        A a2 = new A("hello", new B(666));
        System.out.println(a1.equals(a2));
    }
}

class A {
    String var;
    B b;

    public A(String var, B b) {
        this.var = var;
        this.b = b;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        A a = (A) o;

        if (var != null ? !var.equals(a.var) : a.var != null) return false;
        return b != null ? b.equals(a.b) : a.b == null;
    }

    @Override
    public int hashCode() {
        int result = var != null ? var.hashCode() : 0;
        result = 31 * result + (b != null ? b.hashCode() : 0);
        return result;
    }
}

class B {
    int num;

    public B(int num) {
        this.num = num;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        B b = (B) o;

        return num == b.num;
    }

    @Override
    public int hashCode() {
        return num;
    }
}